package com.lihao.wanandroid.ui.collect

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.lihao.jetpackcore.base.BaseViewModel
import com.lihao.jetpackcore.ext.request
import com.lihao.jetpackcore.state.ResultState
import com.lihao.wanandroid.app.network.callback.CollectUiState
import com.lihao.wanandroid.data.AppRepository
import com.lihao.wanandroid.data.model.CollectEvent

/**
 * 收藏ViewModel
 */
class CollectViewModel(application: Application) : BaseViewModel(application) {

    val collectState: MutableLiveData<CollectUiState> = MutableLiveData()

    /**
     * 收藏文章
     */
    fun collectArticleIn(id: Int) {
        request({ AppRepository.collectArticleIn(id) }, {
            collectState.postValue(
                CollectUiState(isSuccess = true, id = id, collect = true)
            )
        }, {
            collectState.postValue(
                CollectUiState(isSuccess = false, id = id, collect = false, errorMsg = it.errorMsg)
            )
        })
    }

    /**
     * 取消收藏文章
     */
    fun uncollectArticle(id: Int) {
        request({ AppRepository.uncollectArticle(id) }, {
            collectState.postValue(
                CollectUiState(isSuccess = true, id = id, collect = false)
            )
        }, {
            collectState.postValue(
                CollectUiState(isSuccess = false, id = id, collect = true, errorMsg = it.errorMsg)
            )
        })
    }

    /**
     * 收藏URL
     */
    fun collectUrl(name: String, link: String) {
        request({ AppRepository.collectUrl(name, link) }, {
            collectState.postValue(
                CollectUiState(isSuccess = true, id = it.id, collect = true)
            )
        }, {
            collectState.postValue(
                CollectUiState(isSuccess = false, collect = false, errorMsg = it.errorMsg)
            )
        })
    }

//    fun editCollectUrl(id: Int, name: String, link: String) {
//        request({ AppRepository.editCollectUrl(id, name, link) }, {
//            collectState.postValue(
//                CollectUiState(isSuccess = true, id = id, collect = true)
//            )
//        }, {
//            collectState.postValue(
//                CollectUiState(isSuccess = false, collect = false, errorMsg = it.errorMsg)
//            )
//        })
//    }

    /**
     * 取消收藏URL
     */
    fun uncollectUrl(id: Int) {
        request({ AppRepository.uncollectUrl(id) }, {
            collectState.postValue(
                CollectUiState(isSuccess = true, id = id, collect = false)
            )
        }, {
            collectState.postValue(
                CollectUiState(isSuccess = false, id = id, collect = true, errorMsg = it.errorMsg)
            )
        })
    }
}